﻿var me = this,
    draftId = PAI.Global.getUrlData('draftId'),
    controller = this.lookupController(),
    vm = this.lookupViewModel(),
    formDataId = vm.get('NebulogyForm.bizModelId');

var expenseType = ref.ExpenseType.getValue();
var purStore = expenseType == '4' ? ref.datagrid7.getStore() : ref.datagrid2.getStore();
var btn = arguments[2];

//自定义版块错误提示通用方法
//cmp：需检测组件
//getCmpErrors（cmp）：回调函数，返回自定义组件错误信息
//     有错误返回数组，无错误不返回数据
//scope: 回调函数作用域（getCmpErrors）
function customVerification(cmp, getCmpErrors, scope) {
    var block = cmp.up('[isPaiFormBlock]'), //组件所属版块
        cmpErrors = getCmpErrors.call(scope || this, cmp),
        cmpName = cmp.compDisplay || cmp.name; //需检测自定义错误的组件

    if (block) {
        if (!block.activeErrors)
            block.activeErrors = {};

        delete block.activeErrors[cmpName]; //删除上次错误提示
        if (!Ext.isEmpty(cmpErrors)) { //错误不为空，则添加错误提示
            block.activeErrors[cmpName] = cmpErrors;
        }
        block.updateActiveErrors();
    }
    return cmpErrors || [];
}

var viewStatus = vm.get('NebulogyForm.companySection.status');
var activity = vm.get('NebulogyForm.companySection.activity');

//点击Reject和Inquiry的时候校验approverDesc必填
if (requestData.action == "PA_ReturnOriginator" || requestData.action == 'PA_ReturnOriginatorSelfExBack') {

    var process = ['JLRPR201909240001', 'JLRPR201909170002', 'JLRPR201909170001', 'JLRPR201908270001', 'JLRPR201908260001'];

    if (process.includes(vm.get('NebulogyForm.formInfo.folio'))) {

        controller.showMsgTips('New version online, please contact the administrator');
        return false;
    }

    var comments = ref.approverDesc.value.trim();

    var err = customVerification(ref.approverDesc, function (cmp) {
        if (!cmp.getValue() || !cmp.getValue().trim()) {
            return ['Please enter your Comment !'];
        }
    });
    if (err.length) {
        controller.showMsgTips(err);
        return false;
    }
}
//点击CJLR加签的时候校验是否选人
if (requestData.action == "AddsignToCJRL") {
    var cjrlapostille = ref.cjrlapostille.getValue().trim();

    var err = customVerification(ref.cjrlapostille, function (cmp) {
        if (!cmp.getValue()) {
            return ['Please Select Approvers !'];
        }
    });

    if (err.length) {
        controller.showMsgTips(err);
        return false;
    }
}

//重新提交是给SpecialApprovers1赋值
if (requestData.action == "Resubmit") {

    if (vm.get('NebulogyForm.isInquiryCall') == 1) {

        //修改流程摘要
        var PRType = vm.get('NebulogyForm.GeneralInformation.PRName');
        var folio = vm.get('NebulogyForm.formInfo.folio');
        var taskDetail = '{ "en": "' + PRType + '", "zh_CN": "' + PRType + '"}';
        taskDetail = JSON.parse(taskDetail);
        Ext.PAIRest.request({
            ns: PAI.application.serviceUrl,
            url: 'jlr-rest/api/processInstanceObj/update',
            method: "PUT",
            async: false,
            data: {
                "folio": folio,
                "taskDetail": taskDetail,
            },
            success: function (data) {
            },
            failure: function (jsondata) { }
        });

        vm.set('NebulogyForm.isInquiryCall', 0);
        requestData.bizModel.isInquiryCall = 0;
        //所有的验证都通过了.还需要把采购Item的金额最新的TotalPrice 赋值给originalTotalPrice.这样下次Enquiry后的页面记录的originalTotalPrice就是当前最新的值.

        Ext.each(purStore.data.items, function (record) {
            record.set('originalTotalPrice', record.get('TotalPrice'));
        });
    } else {
        //重新发起时给，把多选框中已勾选的值拼接赋值给SpecialApprovers1
        var SpecialApprovers1 = [];

        Ext.each(ref.SpecialApprovers.items.items, function (ctr) {
            if (ctr.checked) {
                SpecialApprovers1.push(ctr.boxLabel);
            }
        });
        vm.set('NebulogyForm.speical.HaveSpecialApprovers1', SpecialApprovers1.length > 0 ? 'yes' : 'no');
        vm.set('NebulogyForm.speical.SpecialApprovers1', '"' + SpecialApprovers1.join('","') + '"');
    }
} else if (viewStatus == 'approval') {
    if (activity == 'Corporate – FME-FA' || activity == 'Corporate – OUV-FA' || activity == 'Corporate -Tooling-FA' || activity == 'Corporate - SE-FA') {

        if (requestData.action == "PA_ReturnOriginatorSelfExBack") {
            //Enquire时，清空FA节点勾选的人          
            var SpecialApprovers1 = [];
            var specialApprovers = vm.get('NebulogyForm.ApproversSelection.SpecialApprovers');
            if (!Ext.isEmpty(vm.get('NebulogyForm.speical.SpecialApprovers1'))) {
                SpecialApprovers1 = vm.get('NebulogyForm.speical.SpecialApprovers1').split(',');
            }

            Ext.each(ref.SpecialApprovers.items.items, function (ctr) {
                if (ctr.checked && !SpecialApprovers1.includes('"' + ctr.boxLabel + '"')) {
                    ctr.setValue(false);
                }
            });
        }
        if (requestData.action == "Approve") {
            //审批时，把审批时新勾选的值，拼接赋值给SpecialApprovers2
            var SpecialApprovers1 = [];
            var SpecialApprovers2 = [];

            if (!Ext.isEmpty(vm.get('NebulogyForm.speical.SpecialApprovers1'))) {
                SpecialApprovers1 = vm.get('NebulogyForm.speical.SpecialApprovers1').split(',');
            }

            Ext.each(ref.SpecialApprovers.items.items, function (ctr) {
                if (ctr.checked && !SpecialApprovers1.includes('"' + ctr.boxLabel + '"')) {
                    SpecialApprovers2.push(ctr.boxLabel);
                }
            });

            vm.set('NebulogyForm.speical.HaveSpecialApprovers2', SpecialApprovers2.length > 0 ? 'yes' : 'no');
            vm.set('NebulogyForm.speical.SpecialApprovers2', '"' + Array.from(new Set(SpecialApprovers2)).join('","') + '"');
        }
    }
}

ref.datagrid3.getStore().clearFilter();

var formData = this.lookupController().getFormData();
if (formData.CompanyAllocation) {
    requestData.bizModel.CompanyAllocation = formData.CompanyAllocation;
}

if (requestData.action == 'PA_ReturnOriginatorSelfExBack') {
    requestData.bizModel.processState = 2;
    requestData.bizModel.isInquiryCall = 1;
} else if (requestData.action == 'PA_ReturnOriginator') {
    requestData.bizModel.processState = 1;
    requestData.bizModel.isInquiryCall = 0;
} else {
    requestData.bizModel.processState = 1;
    requestData.bizModel.isInquiryCall = 0;
}
//点击重新提交的时候再次判断是否需要抄送
if (requestData.action == 'Resubmit') {
    var prType = ref.PRType.getValue();
    var companyC = ref.companyC.getValue();
    var OUVType = ref.OUVType.getValue();
    var isCopyMe = vm.get('NebulogyForm.isCopyMe');

    //当类型为OUV的时候取tga2的值
    if (expenseType == '4') {
        vm.set('NebulogyForm.totalNetAmount', requestData.bizModel.totalAmountList.pi2);
        vm.set('NebulogyForm.totalGrossAmount', requestData.bizModel.totalAmountList.tga2);
    } else {
        vm.set('NebulogyForm.totalNetAmount', requestData.bizModel.totalAmountList.pi1);
        vm.set('NebulogyForm.totalGrossAmount', requestData.bizModel.totalAmountList.tga1);
    }
    var oldId = vm.get('NebulogyForm.oldpurchasingId');
    var newId = requestData.bizModel.purchasingId;
    //是否满足抄送条件
    if (expenseType != '5' && newId != "") {

        //已经抄送过
        if (isCopyMe == 0) {
            //如果第二次选择的采购与第一次不一致，重新抄送
            if (oldId == newId) {
                vm.set('NebulogyForm.isCopyMe', 1);
            } else {
                vm.set('NebulogyForm.isCopyMe', 0);
                vm.set('NebulogyForm.oldpurchasingId', requestData.bizModel.purchasingId);
            }
        } else {
            if (oldId == newId) {
                vm.set('NebulogyForm.isCopyMe', 1);
            } else {
                vm.set('NebulogyForm.isCopyMe', 0);
                vm.set('NebulogyForm.oldpurchasingId', requestData.bizModel.purchasingId);
            }
        }
    } else {
        vm.set('NebulogyForm.isCopyMe', 1);
    }
    //Tooling 提交的时候获取PA 对应的UK
    if (expenseType == '5') {
        var store2 = ref.datagrid2.getStore();
        var paList = [];

        if (store2.data.length) {
            Ext.each(store2.data.items, function (item) {
                paList.push(item.get('ProjectActivity'));
            });

            Ext.PAIRest.request({
                ns: PAI.application.url,
                url: 'last/dictItemObj/customQuery',
                method: "POST",
                async: false,
                data: {
                    "fields": [
                        { "name": "id" },
                        {
                            "exp": "$." + PAI.Global.getLanguage(),
                            "name": "name",
                            "type": "json"
                        },
                        { "name": "code" },
                        { "name": "orderIndex" }
                    ],
                    filter: "t1.pId='a65986df-3037-434f-8825-5db6ebd6fded'"
                },
                success: function (result) {
                    if (result.responseCode == '100') {
                        var ukApprovers = [];
                        Ext.each(result.data, function (rec) {
                            if (Ext.Array.contains(paList, rec.name)) {
                                ukApprovers.push(rec.code);
                            }
                        });
                        vm.set('NebulogyForm.toolingUKApprovers', ukApprovers.join(','));
                    }
                }
            });
        }
    }
}

var SubTotal = 0;

//根据PurchaseItems中NetPrice总和，赋值给SubTotal
for (var i = 0; i < purStore.getCount(); i++) {
    var TotalPrice = purStore.getAt(i).data.TotalPrice;
    SubTotal = floatAdd(SubTotal, TotalPrice);
}
vm.set('NebulogyForm.amount.SubTotal', SubTotal);

//保存Company Alloction 金额
var temp = {};
var store3 = ref.datagrid3.getStore();

for (var i = 0; i < store3.data.items.length; i++) {
    var currentData = store3.data.items[i].data;
    if (null != temp[currentData.Company] || undefined != temp[currentData.Company]) {
        temp[currentData.Company] = temp[currentData.Company] + currentData.Cost;
    } else {
        temp[currentData.Company] = currentData.Cost;
    }
}
vm.set('NebulogyForm.amount.CompanySubTotal', temp);


//点击任何按钮后，不显示召回按钮
if (requestData.action == 'Resubmit' || requestData.action == 'PA_ReturnOriginator' ||
    requestData.action == 'PA_JabilCancel' || requestData.action == 'PA_Terminate' || requestData.action == 'Approve' ||
    requestData.action == 'PA_ReturnOriginatorSelfExBack' || requestData.action == 'PA_RecallNotStarted' || requestData.action == 'PA_Redirect') {
    vm.set('NebulogyForm.isShowRecall', 'false');
    //点击Enquire按钮，在重新提交页面不显示Cancel按钮
    if (requestData.action == 'PA_ReturnOriginatorSelfExBack') {
        vm.set('NebulogyForm.isShowCancel', 'false');
    } else {
        vm.set('NebulogyForm.isShowCancel', 'true');
    }
    //获取转办人名称
    if (requestData.action == 'PA_Redirect') {
        var name = PAI.Global.getAccount().employee.lastName + " " + PAI.Global.getAccount().employee.firstName;
        vm.set('NebulogyForm.administrativePerson', name);
    }
    //流程异常结束默认赋值abnormal
    if (requestData.action == 'PA_JabilCancel' || requestData.action == 'PA_Terminate') {
        vm.set('NebulogyForm.isProcessstate', 'abnormal');
    }
    else if (requestData.action == 'PA_RecallNotStarted') {
        vm.set('NebulogyForm.isProcessstate', 'Recall');
    } else {
        vm.set('NebulogyForm.isProcessstate', 'normal');
    }
}

//加法运算
function floatAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; }
    try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}


var ukCrossCharge = ref.UKCrossCharge.getValue();
//是否扣减
var isDeduction = ['1', '2', '3', '6'].includes(expenseType);
var _company = ref.companyC.getValue();

if (isDeduction && _company == 'JLRC') {
    if (ukCrossCharge == 'UKJLRC' || ukCrossCharge == 'No') {

        var store3 = ref.datagrid3.getStore();
        var arr = [];
        Ext.each(store3.data.items, function (record) {
            var currentData = record.data;
            var company = currentData.Company;

            if (currentData.budgetControl == 'Y' && company == 'JLRC') {
                var pa = currentData.ProjectActivity;

                var paList = vm.get('NebulogyForm.ProjectActivityList');
                var paId = paList.filter((r) => { return r.ProjectActivity == pa })[0].ID;

                var budgetitemId = ref.BudgetItems.getValue();
                var cost = currentData.Cost;

                arr.push({
                    budgetitemId: budgetitemId,
                    projectActiviyId: paId,
                    cost: currentData.Cost,
                    company: company
                });
            }
        });

        vm.set('NebulogyForm.ComplementPRAmount', JSON.stringify(arr));
    }
}

// 1.申请人重新提交(不含answer) ，弹窗提示。
// 2.FA审批，点击approve时弹窗提示。
var isResubmit = false;
var isFA_Approve = activity.endsWith('FA') && requestData.action == 'Approve';
if (requestData.action == "Resubmit") {
    isResubmit = ref.Resubmit.text == 'Resubmit';
}

btn.customTip = '';
if (ref.fiscalYear.getValue().indexOf('_Y') != -1) {
    if (isResubmit || isFA_Approve) {
        var year = ref.fiscalYear.getValue().replace('_Y', '');
        var val = Ext.Date.format(new Date(year), 'y');
        btn.customTitle = 'Warning';
        btn.customTip = 'The request raised relates to the next fiscal year (' + val + '/' + (parseInt(val) + 1) + '). Please confirm before submission.';
    }
}